package com.services.impl;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.bean.Users;
import com.services.LoginServices;
import com.util.DesUtil;
import com.util.MyBatisUtil;
import com.util.XDataConvert;

@Service("loginService")
public class LoginServicesImpl implements LoginServices{

	/**
	 * 用户登录
	 */
	@Override
	public Users login(Users user) {
		try {
			user.setPassword(DesUtil.encrypt(user.getPassword(), user.getYhxh()) );
			String statement = "com.mapper.LoginMapper.Login";// 映射sql的标识字符串
			return MyBatisUtil.getSqlSession().selectOne(statement, user);
		} catch (Exception e) {
			System.out.println("加密系统出错,请联系管理员");
			return null;
		}
	}

	/**
	 * 找回密码
	 */
	@Override
	public String zhmm(Users user) {
		String statement = "com.mapper.LoginMapper.Zhmm";
		Users u = MyBatisUtil.getSqlSession().selectOne(statement, user);
		if(u != null){
			try {
				String Mwpassword = DesUtil.decrypt(DesUtil.encrypt(u.getPassword(), u.getYhxh()), user.getYhxh()); //解密
				//发送到邮箱
				StringBuffer msg = new StringBuffer();
				msg.append("亲爱的 " + u.getName() + " &nbsp;您好：<br/><br/>");
				msg.append("&nbsp;&nbsp;您的密码已经找回[<font color='#007AFF'>" + Mwpassword + "</font>],请妥善保管!<br/><br/>");
				msg.append("&nbsp;&nbsp;<font size='2px'>我们将一如既往、热忱的为您服务！</font>");
				return "已将密码发送至您的邮箱,请注意查收!";
			} catch (Exception e) {
				System.out.println("解密系统出错，请重试!");
				return "解密出错";
			}
		} else {
			return "填写信息有错误,或未注册";
		}
	}

	/**
	 * 上传用户头像 返回 图像
	 */
	
	@Override
	public String scyhtx(String realPath, MultipartFile yhtx) {
		
		String oldName = yhtx.getOriginalFilename();// 文件原名称
		String uuid = XDataConvert.GetUUIDtoString(); //获取生成的uuid
		String tphz = oldName.substring(oldName.lastIndexOf(".", oldName.length()));  //图片后缀名
		String newFileName = uuid + tphz; //生成图片的名称
		
        try {
           //这里使用Apache的FileUtils方法来进行保存
           FileUtils.copyInputStreamToFile(yhtx.getInputStream(), new File(realPath, newFileName));
           System.out.println("文件上传成功");
       } catch (Exception e) {
           System.out.println("文件上传失败");
           e.printStackTrace();
       }
		return newFileName;
	}

	@Override
	public boolean zcxyh(Users user) {
		boolean flag = false;
		System.out.println(user.toString());
		synchronized (user) {
			user.setYhxh(XDataConvert.MaxUsersYhxh());
			String statement = "com.mapper.LoginMapper.Zcxyh";
			int bl = MyBatisUtil.getSqlSession().insert(statement, user);
			if(bl == 1 ){
				flag = true;
			} else {
				flag = false;
			}
		}
		
	    return flag;
	}

}
